#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>

#define PERR(fmt, ...) fprintf( stderr, fmt "\n", ##__VA_ARGS__)
#define PISSIG( set, sig ) fprintf( stdout, #sig ": %s\n", sigismember(set, sig) ? "BLOCKED" : "UNBLOCKED" )

static void *wait_thread( void * )
{
	sigset_t set;

	// from pthread_create manual:
	//  The  new thread inherits a copy of the creating thread's signal mask (pthread_sigmask(3)).
	//  The set of pending signals for the new thread is empty (sigpending(2)).  The new thread does not inherit
	//  the creating thread's alternate signal stack (sigaltstack(2)).
	sigemptyset(&set);
	pthread_sigmask( SIG_BLOCK, NULL, &set );
	PISSIG( &set, SIGHUP );
	PISSIG( &set, SIGINT );
	PISSIG( &set, SIGTERM );
	PISSIG( &set, SIGUSR1 );

	sigemptyset(&set);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGTERM);
	sigaddset(&set, SIGUSR1);

	while( true ) {
		int rc = 0;
		rc = sigwaitinfo( &set, NULL );
		if( rc < 0 ) {
			PERR( "sigwaitinfo failed" );
			exit(EXIT_FAILURE);
		}

		PERR( "got signal %d", rc );
	}
}

int main( int argc, char *argv[] )
{
	sigset_t set;
	sigemptyset(&set);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGTERM);
	sigaddset(&set, SIGUSR1);

	int rc = 0;
	rc = sigprocmask( SIG_BLOCK, &set, NULL );
	// rc = pthread_sigmask( SIG_BLOCK, &set, NULL );
	if( rc != 0 ) {
		PERR( "sigprocmask failed." );
		exit(EXIT_FAILURE);
	}

	pthread_t tid;
	pthread_create( &tid, NULL, wait_thread, NULL );
	pthread_join( tid, NULL );
}

